require('dotenv').config(); // 确保在其他代码之前加载环境变量
const express = require('express');
const cors = require('cors');
const db = require('./db');
// 引入路由并正确命名
const userRouter = require('./routes/user'); 
const closeConfig = require('./routes/closeConfig'); 

const app = express();
const PORT =  3000; // 确保端口号正确



// 配置中间件（顺序必须正确）
app.use(cors({
  origin: 'http://localhost:8080',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
}));
app.use(express.json()); // 必须在路由之前
app.use(express.urlencoded({ extended: true }));

// 挂载路由
app.use('/api', userRouter); 
app.use('/api', closeConfig); 

// 测试路由
app.get('/api/test', (req, res) => {
  res.json({ message: 'Backend is working!' });
});

// 全局错误处理（确保在路由之后）
app.use((req, res, next) => {
  res.status(404).json({ error: 'Route not found' });
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});